import axios from "axios";

export default class CancelToken {
  store: Map<any, any>;
  constructor() {
    this.store = new Map();
  }
  add(config: any) {
    const key = this.getKey(config);
    new axios.CancelToken((cancel) => {
      if (this.store.has(key)) {
        this.remove(config);
      }
      this.store.set(key, cancel);
    });
  }
  remove(config: any) {
    const key = this.getKey(config);
    if (this.store.has(key)) {
      const cancel = this.store.get(key);
      cancel(key);
      this.store.delete(key);
    }
  }
  // 获取唯一的key
  getKey(config: any) {
    const { method, url, params, data } = config;
    return [method, url, params, data].join("-");
  }
}
